package org.itboys.product.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.product.entity.ProductSpecDetail;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by huml on 2016/4/8.
 * 产品规格详情业务
 */
@Service
public class ProductSpecDetailService extends BaseService <ProductSpecDetail, Long> {
    private static final long serialVersionUID = -1615552768790015236L;

    @Resource(name="productDS")
    private MongoDataSource productSpecDetailDateSource;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return productSpecDetailDateSource;
    }

    @Override
    protected Class<ProductSpecDetail> getEntityClass() {
        return ProductSpecDetail.class;
    }

    /**
     * 获取某个产品的规格详情
     * @param productId
     * @return
     */
    public List<ProductSpecDetail> getByProduct(Long productId){
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
        param.put("productId", productId);
        return super.list(param);
    }

    /**
     * 通过产品id删除
     * @param productId
     */
    public void deleteByProductId(Long productId){
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
        param.put("productId", productId);
        delete(param);
    }

    /**
     * 修改产品的规格详情
     * @param param
     * @param productId
     */
    public void insert(String param, Long productId){
        if(StringUtils.isNotBlank(param)){
            deleteByProductId(productId);
            String[]  array = StringUtils.split(param, "***");
            List<ProductSpecDetail> list = Lists.newArrayListWithExpectedSize(array.length);
            for (String string :
                    array) {
                String[] array1 = StringUtils.split(string, ",");
                ProductSpecDetail productSpecDetail = new ProductSpecDetail();
                productSpecDetail.setProductId(productId);
                productSpecDetail.setPrice(array1[2]);
                productSpecDetail.setStock(Long.valueOf(array1[1]));
                String[] array2 = StringUtils.split(array1[0], "-");
                List<Long> categorySpecDetailIds = Lists.newArrayListWithExpectedSize(array2.length);
                for (String string2: array2) {
                    categorySpecDetailIds.add(Long.valueOf(string2));
                }
                productSpecDetail.setCategorySpecDetailIds(categorySpecDetailIds);
                list.add(productSpecDetail);
            }
            batchSave(list);
        }
    }

}
